package com.example.app.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@Component
public class GradioClient {

    private final WebClient webClient;
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 使用构造器注入WebClient
    public GradioClient(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder
                .baseUrl("https://smrqh-medical-chat.hf.space")
                .defaultHeader("Content-Type", "application/json")
                .build();
    }

    /**
     * 向部署在HuggingFace的医疗模型发送提问（非阻塞式）
     *
     * @param prompt 用户提问（如"高血压有哪些症状？"）
     * @return 包含模型回答的Mono
     */
    public Mono<String> getResponse(String prompt) {
        // 构造API请求payload
        Map<String, Object> payload = Map.of(
                "model", "smrqh/medical-deepseek-8b",
                "messages", List.of(Map.of("role", "user", "content", prompt)),
                "max_tokens", 512,
                "temperature", 0.2
        );

        try {
            // 将payload转换为JSON字符串
            String jsonPayload = objectMapper.writeValueAsString(payload);

            return webClient.post()
                    .uri("/v1/chat/completions")
                    .bodyValue(jsonPayload)
                    .retrieve()
                    .bodyToMono(String.class)
                    .flatMap(response -> {
                        try {
                            // 解析JSON响应
                            JsonNode root = objectMapper.readTree(response);
                            JsonNode contentNode = root.path("choices")
                                    .get(0)
                                    .path("message")
                                    .path("content");

                            if (!contentNode.isMissingNode()) {
                                return Mono.just(contentNode.asText());
                            } else {
                                return Mono.just("⚠️ 未找到模型回答内容");
                            }
                        } catch (Exception e) {
                            return Mono.error(new RuntimeException("响应解析失败", e));
                        }
                    })
                    .onErrorResume(e ->
                            Mono.just("❌ 请求失败: " + e.getMessage())
                    );

        } catch (Exception e) {
            return Mono.error(new RuntimeException("请求构造失败", e));
        }
    }
}